from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class Level(models.Model):
    """关卡表 - 游戏关卡配置"""
    level_id = models.AutoField(primary_key=True, verbose_name='关卡唯一ID', db_comment='关卡唯一ID')
    level_name = models.CharField(max_length=100, verbose_name='关卡名称', db_comment='关卡名称')
    difficulty_factor = models.FloatField(default=1.0, verbose_name='难度系数', db_comment='难度系数，用于计算得分权重，范围1.0-5.0')

    class Meta:
        db_table = 'xiangsu_levels'
        db_table_comment = '关卡表-游戏关卡配置'
        verbose_name = '关卡'
        verbose_name_plural = '关卡'

    def __str__(self):
        return str(self.level_name)


class Question(models.Model):
    """题库表 - 环保知识题目库"""
    question_id = models.AutoField(primary_key=True, verbose_name='题目唯一ID', db_comment='题目唯一ID')
    level = models.ForeignKey('Level', on_delete=models.CASCADE, db_column='level_id', verbose_name='所属关卡', db_comment='所属关卡')
    content = models.TextField(verbose_name='题干内容', db_comment='题干内容')
    correct_option_index = models.IntegerField(verbose_name='正确选项序号', default=1, db_comment='正确选项序号(1-4)', help_text='该题目内正确选项的序号，从1开始')
    difficulty_label = models.CharField(max_length=10, default='简单', choices=[('简单', '简单'), ('中等', '中等'), ('困难', '困难')], verbose_name='题目难度', db_comment='题目难度标签')

    class Meta:
        db_table = 'xiangsu_questions'
        db_table_comment = '题库表-环保知识题目库'
        verbose_name = '题目'
        verbose_name_plural = '题目'

    def __str__(self):
        return f'题目{self.question_id} - {self.content[:30]}...'


class QuestionOption(models.Model):
    """题目选项表 - 题目的答案选项"""
    option_id = models.AutoField(primary_key=True, verbose_name='选项唯一ID', db_comment='选项唯一ID')
    question = models.ForeignKey('Question', on_delete=models.CASCADE, db_column='question_id', verbose_name='所属题目', db_comment='所属题目')
    content = models.CharField(max_length=255, verbose_name='选项内容', db_comment='选项内容')

    class Meta:
        db_table = 'xiangsu_question_options'
        db_table_comment = '题目选项表-题目的答案选项'
        verbose_name = '题目选项'
        verbose_name_plural = '题目选项'

    def __str__(self):
        return f'题目{self.question.question_id} - 选项{self.get_option_index()}'
    
    def get_option_index(self):
        """获取该选项在题目中的序号（从1开始）"""
        options = list(self.question.questionoption_set.order_by('option_id').values_list('option_id', flat=True))
        try:
            return options.index(self.option_id) + 1
        except ValueError:
            return 0


class UserAnswer(models.Model):
    """用户答题记录表 - 记录用户的答题历史和成绩"""
    answer_log_id = models.AutoField(primary_key=True, verbose_name='记录唯一ID', db_comment='记录唯一ID')
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE, db_column='user_id', verbose_name='答题用户', db_comment='答题用户', null=True, blank=True)
    question = models.ForeignKey('Question', on_delete=models.CASCADE, db_column='question_id', verbose_name='回答的问题ID', db_comment='回答的问题ID')
    selected_option = models.ForeignKey('QuestionOption', on_delete=models.CASCADE, db_column='selected_option_id', verbose_name='用户选择的选项ID', db_comment='用户选择的选项ID')
    is_correct = models.BooleanField(verbose_name='是否回答正确', db_comment='是否回答正确')
    score_earned = models.IntegerField(default=0, verbose_name='本次得分', db_comment='本次答题获得的分数')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='答题时间', db_comment='答题时间')

    class Meta:
        db_table = 'xiangsu_user_answers'
        db_table_comment = '用户答题记录表-记录用户的答题历史和成绩'
        verbose_name = '用户答题记录'
        verbose_name_plural = '用户答题记录'

    def __str__(self):
        return f'用户{self.user.username if self.user else "未知"}答题记录{self.answer_log_id}'


class UserScore(models.Model):
    """用户积分表 - 记录用户的总积分和排名"""
    user = models.OneToOneField('auth.User', on_delete=models.CASCADE, primary_key=True, verbose_name='用户', db_comment='用户')
    total_score = models.IntegerField(default=0, verbose_name='总积分', db_comment='用户总积分')
    rank = models.IntegerField(default=0, verbose_name='排名', db_comment='用户排名')
    last_updated = models.DateTimeField(auto_now=True, verbose_name='最后更新时间', db_comment='最后更新时间')

    class Meta:
        db_table = 'xiangsu_user_scores'
        db_table_comment = '用户积分表-记录用户的总积分和排名'
        verbose_name = '用户积分'
        verbose_name_plural = '用户积分'

    def __str__(self):
        return f'{self.user.username} - 积分: {self.total_score} - 排名: {self.rank}'
